# coding=utf-8
import socket, socketserver
import threading, getopt, sys, string, logging
from util.Logger import Logger

logger = Logger('HandlerEventServer.log',logging.DEBUG,logging.DEBUG)

def saveEventToDB(client, address):
    try:
        # 设置超时时间
        client.settimeout(500)
        # 接收数据的大小
        buf = client.recv(2048)
        if buf:
            print(buf)
        else:
            logger.debug("pass")
    # 超时后显示退出
    except socket.timeout:
        logger.debug("time out")
    # 关闭与客户端的连接
    client.close()


def main1():
    # 创建socket对象。调用socket构造函数
    # AF_INET为ip地址族，SOCK_STREAM为流套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 将socket绑定到指定地址，第一个参数为ip地址，第二个参数为端口号
    sock.bind(('localhost', port))
    # 设置最多连接数量
    sock.listen(list)
    while True:
        # 服务器套接字通过socket的accept方法等待客户请求一个连接
        client, address = sock.accept()
        thread = threading.Thread(target=saveEventToDB, args=(client, address))
        thread.start()


class HandlerEventServer(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request
        event = conn.recv(2048)
        if event:
            print(event)
        else:
            print("pass")

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass


if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(('10.20.8.22', 18003), HandlerEventServer)
    server.daemon = True
    server.serve_forever(0.1)

    # python handlerEventsServer.py